package org.luxor.commons.rabbitmq.aspect;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.luxor.commons.core.constant.BaseConst;
import org.luxor.commons.rabbitmq.RabbitMqHelper;
import org.luxor.commons.rabbitmq.context.MessageContext;
import org.luxor.commons.rabbitmq.definition.MessageDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Stack;

/**
 * @author Mr.yan @date 2019/10/17
 */
@Aspect
@Component
public class SendMessageAspect {
    private static final Logger log = LoggerFactory.getLogger(SendMessageAspect.class);

    @Resource
    private RabbitMqHelper rabbitMqHelper;

    @Pointcut("@annotation(org.luxor.commons.rabbitmq.annotation.PushMessage)")
    public void annotationPointCut() {
    }


    @Around("annotationPointCut()")
    public Object sendMessage(ProceedingJoinPoint proceed) throws Throwable {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader(BaseConst.TOKEN_NAME);
            if (StringUtils.isBlank(token)) {
                token = StringUtils.EMPTY;
            }
            // 执行当前的方法
            Object result = proceed.proceed();
            // 发送Mq消息
            Stack<MessageDefinition> messageDefintions = MessageContext.getMessageDefintions();
            for (MessageDefinition message : messageDefintions) {
                rabbitMqHelper.sendMessage(message.getExchangeName(), message.getRoutingKey(), message.getContent(), token, message.getExpirationMilliSecond());
            }
            return result;
        } catch (Throwable e) {
            log.error("发送RabbitMessage失败！", e);
            throw e;
        } finally {
            MessageContext.flush();
        }
    }
}
